package usbipstatusmgr

import (
	log "github.com/sirupsen/logrus"
	"sync"
	"time"
)

type UsbIpStatus int

type BusStatusInfo struct {
	AttachUtc uint32
	VendorId  string
}

const (
	UsbIpStatusOK  UsbIpStatus = 0
	UsbIpStatusIng UsbIpStatus = 1
)

type UsbIpStatusMgr struct {
	rwLock    sync.RWMutex
	statusMgr map[string]*BusStatusInfo
}

func NewUsbIpStatusMgr() UsbIpStatusMgrService {
	return &UsbIpStatusMgr{
		statusMgr: make(map[string]*BusStatusInfo),
	}
}

func (mgr *UsbIpStatusMgr) Add(busId, vendorId string) {
	mgr.rwLock.Lock()
	defer mgr.rwLock.Unlock()
	info := mgr.statusMgr[busId]
	if info == nil {
		info = &BusStatusInfo{
			AttachUtc: uint32(time.Now().Unix()),
			VendorId:  vendorId,
		}
	} else {
		info.AttachUtc = uint32(time.Now().Unix())
		info.VendorId = vendorId
	}
	mgr.statusMgr[busId] = info
	log.Infof("UsbIpStatusMgr Add bus id:%v vendorId:%v", busId, vendorId)
}

func (mgr *UsbIpStatusMgr) Get(busId string) *BusStatusInfo {
	mgr.rwLock.RLock()
	defer mgr.rwLock.RUnlock()
	return mgr.statusMgr[busId]
}

func (mgr *UsbIpStatusMgr) Remove(busId string) {
	mgr.rwLock.Lock()
	defer mgr.rwLock.Unlock()
	delete(mgr.statusMgr, busId)
	log.Infof("UsbIpStatusMgr Remove bus id:%v", busId)
}
